{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "from torch.autograd import Variable\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Model(nn.Module):\n",
    "    \n",
    "    def __init__(self):\n",
    "        super(Model,self).__init__()\n",
    "        \n",
    "        self.conv0 = nn.Conv2d(1, 16, kernel_size=3, padding=5)\n",
    "        self.conv1 = nn.Conv2d(16, 32, kernel_size=3)\n",
    "\n",
    "    def forward(self, x):\n",
    "        h = self.conv0(x)\n",
    "        h = self.conv1(h)\n",
    "        return h\n",
    "    \n",
    "model = Model()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "from torch.autograd import Variable\n",
    "import numpy as np\n",
    "\n",
    "class SizeEstimator(object):\n",
    "\n",
    "    def __init__(self, model, input_size=(1,1,32,32), bits=32):\n",
    "        '''\n",
    "        Estimates the size of PyTorch models in memory\n",
    "        for a given input size\n",
    "        '''\n",
    "        self.model = model\n",
    "        self.input_size = input_size\n",
    "        self.bits = 32\n",
    "        return\n",
    "\n",
    "    def get_parameter_sizes(self):\n",
    "        '''Get sizes of all parameters in `model`'''\n",
    "        mods = list(model.modules())\n",
    "        for i in range(1,len(mods)):\n",
    "            m = mods[i]\n",
    "            p = list(m.parameters())\n",
    "            sizes = []\n",
    "            for j in range(len(p)):\n",
    "                sizes.append(np.array(p[j].size()))\n",
    "\n",
    "        self.param_sizes = sizes\n",
    "        return\n",
    "\n",
    "    def get_output_sizes(self):\n",
    "        '''Run sample input through each layer to get output sizes'''\n",
    "        input_ = Variable(torch.FloatTensor(*self.input_size), volatile=True)\n",
    "        mods = list(model.modules())\n",
    "        out_sizes = []\n",
    "        for i in range(1, len(mods)):\n",
    "            m = mods[i]\n",
    "            out = m(input_)\n",
    "            out_sizes.append(np.array(out.size()))\n",
    "            input_ = out\n",
    "\n",
    "        self.out_sizes = out_sizes\n",
    "        return\n",
    "\n",
    "    def calc_param_bits(self):\n",
    "        '''Calculate total number of bits to store `model` parameters'''\n",
    "        total_bits = 0\n",
    "        for i in range(len(self.param_sizes)):\n",
    "            s = self.param_sizes[i]\n",
    "            bits = np.prod(np.array(s))*self.bits\n",
    "            total_bits += bits\n",
    "        self.param_bits = total_bits\n",
    "        return\n",
    "\n",
    "    def calc_forward_backward_bits(self):\n",
    "        '''Calculate bits to store forward and backward pass'''\n",
    "        total_bits = 0\n",
    "        for i in range(len(self.out_sizes)):\n",
    "            s = self.out_sizes[i]\n",
    "            bits = np.prod(np.array(s))*self.bits\n",
    "            total_bits += bits\n",
    "        # multiply by 2 for both forward AND backward\n",
    "        self.forward_backward_bits = (total_bits*2)\n",
    "        return\n",
    "\n",
    "    def calc_input_bits(self):\n",
    "        '''Calculate bits to store input'''\n",
    "        self.input_bits = np.prod(np.array(self.input_size))*self.bits\n",
    "        return\n",
    "\n",
    "    def estimate_size(self):\n",
    "        '''Estimate model size in memory in megabytes and bits'''\n",
    "        self.get_parameter_sizes()\n",
    "        self.get_output_sizes()\n",
    "        self.calc_param_bits()\n",
    "        self.calc_forward_backward_bits()\n",
    "        self.calc_input_bits()\n",
    "        total = self.param_bits + self.forward_backward_bits + self.input_bits\n",
    "\n",
    "        total_megabytes = (total/8)/(1024**2)\n",
    "        return total_megabytes, total\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(0.5694580078125, 4776960)\n"
     ]
    }
   ],
   "source": [
    "se = SizeEstimator(model)\n",
    "print(se.estimate_size())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(408.2833251953125, 3424928768)\n"
     ]
    }
   ],
   "source": [
    "se = SizeEstimator(model, input_size=(16,1,256,256))\n",
    "print(se.estimate_size())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
